package com.ken.forum.services.impl;

import com.alibaba.druid.util.StringUtils;
import com.ken.forum.common.AppResult;
import com.ken.forum.common.ResultCode;
import com.ken.forum.dao.UserMapper;
import com.ken.forum.exception.ApplicationException;
import com.ken.forum.model.User;
import com.ken.forum.services.IUserService;
import com.ken.forum.utils.MD5Util;
import com.ken.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


//Service 层（服务层）是项目中负责业务逻辑处理的部分。
// 它位于控制器层（Controller）和数据访问层（DAO）之间，
// 主要作用是封装业务逻辑，确保代码的职责分离，简化控制器的代码结构，
// 使其专注于处理 HTTP 请求，而将复杂的业务逻辑放置在 Service 层。

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        if (user == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
// 查询当前⽤⼾是否存在
        User existUser = userMapper.selectByUserName(user.getUsername());
        if (existUser != null) {
// 记录⽇志
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username = " + user.getUsername());
// 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
// 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
// 性别赋默认值
            user.setGender((byte) 2);
        }
        // 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            // 记录⽇志
            log.info(ResultCode.FAILED_CREATE.toString() + "username = " + user.getUsername());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 记录⽇志
        log.info("新增⽤⼾成功：username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 根据⽤⼾名获取⽤⼾信息
        User user = selectByUserName(username);
        // ⽤⼾不存在抛出异常
        if (user == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 校验密码是否正确
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            // 记录⽇志
            log.info(ResultCode.FAILED_LOGIN.toString() + "username = " + username + ", password = " + password);
            // 密码不正确抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 校验通过，返回⽤⼾信息
        return user;
    }


    @Override
    public User selectById(Long id) {
        if (id < 0 || id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }


    /**
     * 用户发帖数加一
     *
     * @param id
     */
    @Override
    public void addOneArticleCountById(Long id) {
        if (id < 0 || id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询现有的用户信息
        User user = selectById(id);
        // 校验用户是否为空
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        user.setArticleCount(user.getArticleCount() + 1);
        user.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(user);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }


    /**
     * 用户发帖数减一
     *
     * @param id
     */
    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            // 打印⽇志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询⽤⼾信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印⽇志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新⽤⼾的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1之后，⽤⼾的发帖数是否⼩于0
        if (updateUser.getArticleCount() < 0) {
            // 如果⼩于0，则设置为0
            updateUser.setArticleCount(0);
        }
        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 定义一个标识
        boolean checkParam = false;
        //更新用户
        User updateUser = new User();
        updateUser.setId(user.getId());
        //用户名
        if (!StringUtils.isEmpty(user.getUsername())) {
            User user1 = selectByUserName(user.getUsername());
            if (user1 == null) {
                updateUser.setUsername(user.getUsername());
                checkParam = true;
            } else {
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }

        }
        //昵称
        if (!StringUtils.isEmpty(user.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkParam = true;
        }
        //性别
        if (user.getGender() != null) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 校验有效性 0女 1男 2保密
            if (updateUser.getGender() < 0 || updateUser.getGender() > 2) {
                // 处理方式1：设置成默认值
                // 处理方式2：设置为null, 表示保持原来的性别，不更新数据库
                updateUser.setGender((byte) 2);
            }
            // 更新标识
            checkParam = true;

        }
        //电话号码
        if (!StringUtils.isEmpty(user.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkParam = true;
        }
        //邮箱
        if (!StringUtils.isEmpty(user.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkParam = true;
        }
        //简介
        if (!StringUtils.isEmpty(user.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkParam = true;
        }

        if (checkParam == false) {
            throw new ApplicationException("所有信息不能同时为空");
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id < 0 || id == null || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectById(id);
        if (user == null || user.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if (!MD5Util.verifyOriginalAndCiphertext(oldPassword, user.getSalt(), user.getPassword())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PASSWORD_CHECK.toString() + " user id = " + id + ", old password = " + oldPassword);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PASSWORD_CHECK));
        }
        String salt = UUIDUtil.UUID_32();
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(MD5Util.md5Salt(newPassword, salt));
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }


}
